package cn.sccl.common.util;

import java.lang.reflect.Field;

/**
 * Created by 杨浩宇 on 2015-11-27.
 */
public class BeanUtils {
    /**
     * 根据属性名查询属性。如果属性名在父类中，则递归到父类中查询
     *
     * @param cls       需要查找属性的类
     * @param fieldName 属性名
     * @return
     */
    public static Field getField(Class<?> cls, String fieldName) {
        try {
            return cls.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            if (!cls.isAssignableFrom(Object.class)) {
                return getField(cls.getSuperclass(), fieldName);
            } else {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage(), e.getCause());
            }
        }
    }

    public static Object getValue(Object obj, String fieldName) {
        Field field = getField(obj.getClass(), fieldName);
        Object value = null;
        if (field != null) {
            if (field.isAccessible()) {
                try {
                    value = field.get(obj);
                } catch (IllegalAccessException ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex.getMessage(), ex.getCause());
                }

            } else {
                field.setAccessible(true);
                try {
                    value = field.get(obj);
                } catch (IllegalAccessException ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex.getMessage(), ex.getCause());
                }
                field.setAccessible(false);
            }
        }
        return value;
    }

    public static void setFieldValue(Object obj, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        Field field = obj.getClass().getDeclaredField(fieldName);
        if (field.isAccessible()) {
            field.set(obj, value);
        } else {
            field.setAccessible(true);
            field.set(obj, value);
            field.setAccessible(false);
        }
    }
}
